package com.ktjiaoyu.crm.config.shiro;

import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.redis.RedisTemplateUtil;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 自定义Realm
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RightService rightService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    //Redis中缓存数据的key前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count:"; //登录次数计数
    private String SHIRO_IS_LOCK = "shirl_is_lock:";         //锁定用户登录

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("调用doGetAuthorizationInfo()获取权限信息..........");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取权限信息
        User user = (User)principals.getPrimaryPrincipal();
        //从数据库查询角色信息
        Role roleByUserId = roleService.findRoleByUserId(user.getUsrId());
        //静态授权：授予Subject(用户)相应角色权限
        info.addRole(roleByUserId.getRoleName());
        //Shiro动态授权：从数据库中查询该用户拥有的权限
        Set<String> rights = rightService.findRightsByRoleName(roleByUserId.getRoleId());
        info.addStringPermissions(rights);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用doGetAuthenticationInfo()获取身份信息..........");
        //获取身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //每次访问，登录次数+1
        redisTemplateUtil.incr(SHIRO_LOGIN_COUNT+token.getUsername(),1);
        //获取token中的用户名
        String username = token.getUsername();

        //计数大于 5 时，设置用户被锁定一小时，清空登录计数
        if(Integer.parseInt(redisTemplateUtil.get(SHIRO_LOGIN_COUNT+token.getUsername()).toString())>5){
            redisTemplateUtil.set(SHIRO_IS_LOCK+token.getUsername(),"LOCK");
            //锁定用户一小时，设置Redis过期时间，单位S
            redisTemplateUtil.expire(SHIRO_IS_LOCK+token.getUsername(),3600);
            //清空登录计数
            redisTemplateUtil.del(SHIRO_LOGIN_COUNT+token.getUsername());
        }

        //判断用户是否锁定
        if("LOCK".equals(redisTemplateUtil.get(SHIRO_IS_LOCK+token.getUsername()))) throw new DisabledAccountException();

        //根据用户名调用用户信息
        User user = userService.getUesrByName(username);
        if(user == null) throw new UnknownAccountException();   //账号错误
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException(); //账号被锁定
        //principal：身份
        //credentials：凭证
        //realmName：当前Realm的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUsrPassword(),ByteSource.Util.bytes("czkt"),getName());

        return info;
    }

    /**
     * 清空当前认证用户权限缓存
     */
    public void clearMyCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    /**
     * 清空所有用户权限缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        if (this.isAuthorizationCachingEnabled()) { // 权限缓存是否可用
            Cache<Object, AuthorizationInfo> cache = null;
            CacheManager cacheManager = this.getCacheManager();
            if (cacheManager != null) {
                String cacheName = this.getAuthorizationCacheName(); // 获得权限缓存名称
                cache = cacheManager.getCache(cacheName); // 获得权限缓存
            }
            if (cache != null) {
                cache.clear(); // 清空
            }
        }
    }
}
